<template>
  <div>
    <div style="padding: 18px; border-bottom: solid 1px #EEE">
      <el-input v-model="newRole" placeholder="请输入角色名称" style="width: 200px;" />
      <el-button type="primary" @click="confirmCreate()">创建新角色</el-button>
    </div>
    <el-table
      ref="roleTable"
      :data="roleList"
      style="width: 100%"
      @expand-change="fetchRolePrivilege"
    >
      <el-table-column type="expand">
        <template v-slot="{row}">
          <div class="buttons">
            <el-button size="small" @click="setCheckedAll">全选</el-button>
            <el-button size="small" @click="resetChecked">清空</el-button>
            <el-button type="primary" size="small" @click="setRoleFunctions(row)">提交</el-button>
          </div>
          <el-tree
            ref="permissionTree"
            :data="permissionList"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="checkedKeys"
            :props="defaultProps"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="角色ID"
        prop="id"
        width="120"
      />
      <el-table-column
        label="角色名称"
      >
        <template v-slot="{row}">
          <template v-if="row.edit">
            <el-input v-model="row.roleName" class="edit-input" size="small" style="width:80" />
            <el-button
              class="cancel-btn"
              size="small"
              icon="el-icon-refresh"
              type="warning"
              @click="row.edit = !row.edit"
            >
              放弃
            </el-button>
          </template>
          <span v-else>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="角色状态"
        width="120"
      >
        <template v-slot="scope">
          <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status | statusName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
      >
        <template v-slot="{row}">
          <template v-if="row.edit">
            <el-button
              type="success"
              size="small"
              icon="el-icon-check"
              @click="confirmEdit(row)"
            >
              提交
            </el-button>
          </template>
          <el-button
            v-else
            type="primary"
            size="small"
            icon="el-icon-edit"
            @click="row.edit = !row.edit"
          >
            编辑
          </el-button>
          <el-button v-if="row.status" type="danger" size="small" icon="el-icon-close" @click="confirmStatus(row)">停用</el-button>
          <el-button v-else type="success" size="small" icon="el-icon-check" @click="confirmStatus(row)">恢复</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { getRoleList, editRoleStatus, addRole, editRole, getRoleFunction, setRoleFunction, getAllFucntion } from '@/api/admin'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'gray',
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    },
    statusName(status) {
      const statusMap = {
        0: '无效',
        1: '有效'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      newRole: '',
      roleList: [],
      checkedKeys: [],
      permissionList: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  created() {
    this.fetchList()
    this.fetchFunctionList()
  },
  methods: {
    fetchList() {
      getRoleList().then(response => {
        console.log(response)
        this.roleList = response.data
        this.roleList = response.data.map(v => {
          this.$set(v, 'edit', false)
          v.origName = v.roleName
          return v
        })
      })
    },
    fetchFunctionList() {
      getAllFucntion().then(response => {
        console.log(response)
        this.permissionList = response.data
      })
    },
    confirmCreate() {
      if (!this.newRole) {
        this.$notify({
          title: '操作成功',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
        return
      }
      addRole(this.newRole).then(response => {
        this.newRole = ''
        this.$notify({
          title: '操作成功',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
        this.fetchList()
      })
    },
    confirmEdit(row) {
      console.log('confirm edit: ', row)
      editRole(row).then(response => {
        row.edit = !row.edit
        this.$notify({
          title: '操作成功',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    confirmStatus(row) {
      const status = 1 - row.status
      editRoleStatus(row.id, status).then(response => {
        row.status = status
        this.$notify({
          title: '操作成功',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    async fetchRolePrivilege(row, expandedRows) {
      if (expandedRows.length > 1) {
        this.roleList.forEach(ele => {
          if (ele.id !== row.id) {
            this.$refs.roleTable.toggleRowExpansion(ele, false)
          }
        })
      }
      /**
       * 由于有自动关闭其他行的操作，所以次函数可能会被调用两次
       * 所以只对展开的行做数据操作，否则会报错
       */
      if (expandedRows.length > 0) {
        await getRoleFunction(row.id).then(response => {
          const { data } = response
          this.$nextTick(() => {
            if (row.id !== 10000) {
              this.checkedKeys = data.map(value => {
                if (value.nodeType === 0) {
                  return value.permisId
                }
              })
            } else {
              this.checkedKeys = data.map(value => {
                return value.permisId
              })
            }
            this.$refs.permissionTree.setCheckedKeys(this.checkedKeys)
          })
        })
      }
    },
    setRoleFunctions(row) {
      const permissionTrees = this.$refs.permissionTree.getCheckedNodes(false, true)
      console.log('----------permission_tree', permissionTrees)
      setRoleFunction(row.id, permissionTrees).then(response => {
        this.$notify({
          title: '操作成功',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    setCheckedAll() {
      this.checkedKeys = this.permissionList.map(v => {
        return v.id
      })
      this.$refs.permissionTree.setCheckedKeys(this.checkedKeys)
    },
    resetChecked() {
      this.$refs.permissionTree.setCheckedKeys([])
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
